from flask import Flask
from flask import request
from flask import send_file
import numpy as np
import PIL.Image as Image
import random
import os
import jieba
from scipy.misc import imread  # 这是一个处理图像的函数1
#import wordcloud
from wordcloud import WordCloud
from wordcloud import STOPWORDS
from wordcloud import ImageColorGenerator
import matplotlib.pyplot as plt
from io import BytesIO
import io
app = Flask(__name__, static_folder='', static_url_path='')

# 该函数的作用就是把屏蔽词去掉，使用这个函数就不用在WordCloud参数中添加stopwords参数了
# 把你需要屏蔽的词全部放入一个stopwords文本文件里即可
def stop_words(texts):
    words_list = []
    word_generator = jieba.cut(texts, cut_all=False)  # 返回的是一个迭代器
    with open('C:/Users/eaooql/Desktop/1.txt', encoding='gb18030', errors='ignore') as f:
        str_text = f.read()
        unicode_text = str_text  # 把str格式转成unicode格式
        f.close()  # stopwords文本中词的格式是'一词一行'
    for word in word_generator:
        if word.strip() not in unicode_text:
            words_list.append(word)
    return ' '.join(words_list)  # 注意是空格

@app.route('/')
def index():
    return app.send_static_file('index.html')
@app.route('/upload',methods=['GET','POST'])
def upload():
    if request.method == "POST":
        file = request.files['txt']
        files = request.files['img']
        print(files.filename, file.filename)
        back_color = imread(files)  # 解析该图片
        file_name = file.filename
    return "22222"
@app.route('/uploads',methods=['GET','POST'])
def uploads():

        if request.method == "POST":
            file = request.files['txt']
            files = request.files['img']

            # file_name = "test.csv"
            # file_name = file.filename
            # print(file.read())
            back_color = imread(files)  # 解析该图片
            files.flush()
            files.close()
            wc = WordCloud(background_color='white',  # 背景颜色
                           max_words=1000,  # 最大词数
                           mask=back_color,  # 以该参数值作图绘制词云，这个参数不为空时，width和height会被忽略
                           max_font_size=100,  # 显示字体的最大值
                           #stopwords=STOPWORDS.add('1'),  # 使用内置的屏蔽词，再添加'苟利国'
                           font_path="D://font//wawa.ttf",  # 解决显示口字型乱码问题，可进入C:/Windows/Fonts/目录更换字体
                           random_state=42,  # 为每个词返回一个PIL颜色
                           width=1000,  # 图片的宽
                           height=860  # 图片的长
                           )
            # WordCloud各含义参数请点击 wordcloud参数

            # 添加自己的词库分词，比如添加'金三胖'到jieba词库后，当你处理的文本中含有金三胖这个词，
            # 就会直接将'金三胖'当作一个词，而不会得到'金三'或'三胖'这样的词
            # jieba.add_word('金三胖')

            # 打开词源的文本文件
            # text = open('C:/Users/eaooql/Desktop/dora.txt').read()
            text = stop_words(file.read())
            file.flush()
            file.close()
            wc.generate(text)
            # 基于彩色图像生成相应彩色
            image_colors = ImageColorGenerator(back_color)
            # print(image_colors)
            # 显示图片
            plt.imshow(wc)
            # 关闭坐标轴
            plt.axis('off')
            # 绘制词云
            plt.figure()
            plt.imshow(wc.recolor(color_func=image_colors))

            # 保存图片
            #wc.to_file("D://" + str(random.randint(1, 100)) + "zjb.png")
            # file.save(os.path.join('templates\\files', file_name))
            # print(wc.to_array())
            # im = Image.open("D://12.png")
            arr = np.array(wc)

            # 转换为数组
            # global new_im
            new_im = Image.fromarray(arr)
            # 转换为图片
            # new_im.show()
            # 图片的显示
            # global byte_io
            # byte_io = BytesIO()
            # 页面上显示图片
            # new_im.save(byte_io, 'PNG')
            # byte_io.seek(0)
            plt.close()

            """
            本地保存的格式与页面显示的不同
            页面显示的清晰些  本地的较模糊
            """
        return _serve_pil_image(new_im)


def _serve_pil_image(pil_img):
    img_io = BytesIO()
    pil_img.save(img_io, 'PNG')
    img_io.seek(0)

    return send_file(img_io, mimetype='image/png', cache_timeout=0)







if __name__ == '__main__':
    app.run(threaded=True)